package com.es.common.aspect;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;

@Aspect
@Component
public class LogAspect {
	/**
	 * https://blog.csdn.net/kevin12306/article/details/51194669
	 */
	
	@Autowired
	private DefaultMQProducer defaultProducer;
	
	@Pointcut("execution(public * com.es.web.*.controller.*.*(..))")
	public void webLog(){}
	@Before("webLog()")
	public void deBefore(){
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		Map<String, String[]> map = request.getParameterMap();
		
		/*for (Map.Entry<String, String[]> entry : map.entrySet()) {
			String name = entry.getKey();
			String[] values = entry.getValue();
			System.out.println(name);
			System.out.println("值是：");
			for (int i = 0; i < values.length; i++) {
				System.out.println(values[i]);
			}
		}*/
		String topic = "topicTest";
		String tags = "tagA";
		String json = JSONObject.toJSONString(map);
		MessageExt msg = new MessageExt();
		msg.setTopic(topic);
		msg.setTags(tags);
		msg.setBody(json.getBytes());
		try {
			defaultProducer.send(msg, new SendCallback() {
				
				@Override
				public void onSuccess(SendResult sendResult) {
					System.out.println(sendResult.getSendStatus());
					
				}
				
				@Override
				public void onException(Throwable e) {
						System.out.println(e);
				}
			});
		} catch (MQClientException e) {
			e.printStackTrace();
		} catch (RemotingException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
